package com.bilin.coin.network;

import androidx.annotation.NonNull;

import android.util.Log;

import com.bilin.coin.ApiConstant;
import com.bilin.coin.BuildConfig;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.LogUtlis;
import com.bilin.coin.utils.SharedPreferencesUtils;

import java.net.Proxy;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import kt.com.bilin.coin.common.ServiceConfig;
import kt.com.bilin.coin.utils.Logger;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2018/3/27.
 */

public class RetrofitConfig {

    private OkHttpClient okHttpClient;

    private Retrofit.Builder retrofit = new Retrofit.Builder();


    private static RetrofitConfig retrofitConfig;

    /**
     * 主url的路径 http://47.94.132.116:8888  正式服务器http://mobile.btbank.io
     */


  /*  public String strBaseUrl = BuildConfig.DEBUG ? ApiConstant.BaseUrl : ApiConstant.BaseUrl;
    public static String newsUrl = BuildConfig.DEBUG ? ApiConstant.BaseUrl + "/news/app-detail?id=" : ApiConstant.BaseUrl + "/news/app-detail?id=";*/
    public String strBaseUrl = BuildConfig.DEBUG ? ServiceConfig.INSTANCE.getCurrentServiceConfig().getApiUrl() : ApiConstant.BaseUrl;
    public static String newsUrl = BuildConfig.DEBUG ? "http://192.168.1.222:11112" + "/news/app-detail?id=" : ApiConstant.BaseUrl + "/news/app-detail?id=";


    public static RetrofitConfig initRetrofitConfig() {
        if (retrofitConfig == null) {
            synchronized (RetrofitConfig.class) {
                if (retrofitConfig == null) {
                    retrofitConfig = new RetrofitConfig();
                }
            }
        }
        return retrofitConfig;
    }


    @NonNull
    private Retrofit.Builder Factory() {

        return retrofit
                .client(OkHttpClient())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    @NonNull
    private Retrofit.Builder Factory(OkHttpClient okHttpClient) {

        return retrofit
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }


    public Retrofit.Builder baseUrl(String baseUrl) {
        if (baseUrl == null) {
            baseUrl = strBaseUrl;
        }
        return Factory().baseUrl(baseUrl);
    }

    public Retrofit.Builder baseUrl(String baseUrl, OkHttpClient okHttpClient) {
        if (baseUrl == null) {
            baseUrl = strBaseUrl;
        }
        return Factory(okHttpClient).baseUrl(baseUrl);
    }

    /**
     * 单例okhttpclient对象
     *
     * @return
     */
    public OkHttpClient OkHttpClient() {

        if (okHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                            .readTimeout(60000L, TimeUnit.MILLISECONDS)
                            .proxy(Proxy.NO_PROXY)
                            .addInterceptor(getHttpLoggingInterceptor())
                            .cookieJar(new CookieJar() {
                                @Override
                                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                                    //读取cookie并缓存在本地
                                    String Cookie = SharedPreferencesUtils.getInstance().getString("Cookie", "");
                                    Map<String, String> mapCookie = GsonUtil.GsonToMaps(Cookie);
                                    if (mapCookie == null) {
                                        mapCookie = new LinkedHashMap<>();
                                    }

                                    if (cookies != null && cookies.size() > 0) {
                                        for (int i = 0; i < cookies.size(); i++) {
                                            mapCookie.put(cookies.get(i).name(), cookies.get(i).value());

                                            LogUtlis.e(mapCookie.toString());
                                        }
                                        String strCookie = GsonUtil.GsonString(mapCookie);
                                        SharedPreferencesUtils.getInstance().saveData("Cookie", strCookie);
                                    }
                                }

                                @Override
                                public List<Cookie> loadForRequest(HttpUrl url) {

                                    return new ArrayList<>();
                                }
                            })
                            .build();
                }
            }
        }

        return okHttpClient;
    }


    /**
     * 日志输出
     * 自行判定是否添加
     *
     * @return
     */
    public HttpLoggingInterceptor getHttpLoggingInterceptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
//                if (BuildConfig.DEBUG) {
                    Logger.e("Api请求==>" + message);
//                }
            }
        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }
}
